package com.duowan.cms.action;

import java.io.IOException;
import java.util.Date;
import java.util.List;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;

import com.duowan.cms.common.exception.BaseCheckedException;
import com.duowan.cms.common.util.IdManager;
import com.duowan.cms.common.util.StringUtil;
import com.duowan.cms.dto.channel.ChannelInfo;
import com.duowan.cms.dto.tag.TagCategory;
import com.duowan.cms.dto.tag.TagInfo;
import com.duowan.cms.service.channel.ChannelService;
import com.duowan.cms.service.tag.TagService;

@Controller
public class TagController extends AbstractController {

	@Autowired
	private ChannelService channelService;
	
	@Autowired
	private TagService tagService;
	
	private static Logger logger = Logger.getLogger(FileController.class);
	
	@RequestMapping(value = "/tag/tagManage", method = RequestMethod.GET)
	public String tagManage(HttpServletRequest request,HttpServletResponse response) throws IOException {
		String channelId = request.getParameter("channelId");
		List<TagInfo> tagInfoList = tagService.getAllTagsInChannel(channelId);
		request.setAttribute("tagInfoList", tagInfoList);
		return "/tag/tag_manage";
	}
	@RequestMapping(value = "/tag/addAlias", method = RequestMethod.GET)
	public String addAlias(HttpServletRequest request,HttpServletResponse response) throws IOException {
		String channelId = request.getParameter("channelId");
		String alias = request.getParameter("parentName");//需要增加的别名
		String tagName = request.getParameter("tagName");//用parentName存放需要增加别名的标签
		tagService.addAlias(channelId, tagName, alias);
		return "redirect:/tag/tagManage.do?channelId=" + channelId;
	}
	/**
	 * 图与非图的转换
	 */
	@RequestMapping(value = "/tag/exchangeTagImage", method = RequestMethod.GET)
	public String exchangeTagImage(HttpServletRequest request,HttpServletResponse response) throws IOException {
		String channelId = request.getParameter("channelId");
		String isTagImageStr = request.getParameter("parentName");
		String tagName = request.getParameter("tagName");
		tagService.exchangeTagImage(channelId, tagName, Boolean.parseBoolean(isTagImageStr));
		return "redirect:/tag/tagManage.do?channelId=" + channelId;
	}
	
	@RequestMapping(value = "/tag/addTag", method = RequestMethod.GET)
	public String addTag(HttpServletRequest request,HttpServletResponse response) throws IOException {
		String channelId = request.getParameter("channelId");
		String type = request.getParameter("type");
		String tagName = request.getParameter("tagName");
		String parentName = request.getParameter("parentName")==null ? "" :  request.getParameter("parentName");
		String parentTree = request.getParameter("parentTree")==null ? "" :  request.getParameter("parentTree");
		logger.info("频道["+channelId+"]添加["+TagCategory.getInstance(type).getDisplay()+"]类型的标签[name="+tagName.trim()+"]");
		TagInfo tagInfo = new TagInfo();
		tagInfo.setCategory(TagCategory.getInstance(type));
		tagInfo.setChannelInfo(channelService.getById(channelId));
		tagInfo.setName(tagName.trim());
		tagInfo.setParentName(parentName);
		tagInfo.setTree(this.getTree(parentTree, tagName));
		tagInfo.setUpdateTime(new Date());
		tagInfo.setId(IdManager.generateId());
		tagService.addChild(tagInfo);
		
		return "redirect:/tag/tagManage.do?channelId=" + channelId;
	}
	
	@RequestMapping(value = "/tag/editTag", method = RequestMethod.GET)
	public String editTag(HttpServletRequest request,HttpServletResponse response) throws IOException {
		String channelId = request.getParameter("channelId");
		String tagName = request.getParameter("tagName");
		String parentTree = request.getParameter("parentTree")==null ? "" :  request.getParameter("parentTree");

		tagService.updateTagName(channelId, parentTree, tagName);
		return "redirect:/tag/tagManage.do?channelId=" + channelId;
	}
	
	@RequestMapping(value = "/tag/deleteTag", method = RequestMethod.GET)
	public String deleteTag(HttpServletRequest request,HttpServletResponse response,
				@ModelAttribute("tagInfo") TagInfo tagInfo) throws IOException {
		String channelId = request.getParameter("channelId");
		String tagName = request.getParameter("tagName");
		ChannelInfo channelInfo = channelService.getById(channelId);
		logger.info("删除频道["+channelInfo.getName() + "]的标签[name="+tagName+"]");
		tagInfo.setName(tagName);
		tagInfo.setChannelInfo(channelInfo);
		tagService.deleteTag(tagInfo);
		return "redirect:/tag/tagManage.do?channelId=" + channelId; 
	}
	
	@RequestMapping(value = "/tag/removeTagAllMsg", method = RequestMethod.GET)
	public String removeTagAllMsg(HttpServletRequest request,HttpServletResponse response,
				@ModelAttribute("tagInfo") TagInfo tagInfo) throws IOException {
		String channelId = request.getParameter("channelId");
		String tagName = request.getParameter("tagName");
		ChannelInfo channelInfo = channelService.getById(channelId);
		logger.info("彻底删除频道["+channelInfo.getName() + "]的标签[name="+tagName+"]");
		tagInfo.setName(tagName);
		tagInfo.setChannelInfo(channelInfo);
		tagService.removeTagAllMsg(tagInfo);
		return "redirect:/tag/tagManage.do?channelId=" + channelId; 
	}
	
	@RequestMapping(value = "/tag/cutTag", method = RequestMethod.GET)
	public void cutTag(HttpServletRequest request,HttpServletResponse response) throws IOException {
		String channelId = request.getParameter("channelId");
		String tagName = request.getParameter("tagName");
		TagInfo tagInfo = tagService.getByChannelIdAndName(channelId, tagName);
		response.setCharacterEncoding("UTF-8");
		if (tagInfo.getCategory() == TagCategory.SPECIAL) {
			response.getWriter().write("error:特殊tag不能剪切");
			return;
		}
		if(tagInfo.getTagDepth() > 4){
			response.getWriter().write("error:目录满级了，不能剪切");
			return;
		}
		request.getSession().setAttribute("tagcut", tagInfo.getChannelId() + ","
					+ tagInfo.getName() );
	}
	@RequestMapping(value = "/tag/pasteTag", method = RequestMethod.GET)
	public void pasteTag(HttpServletRequest request,HttpServletResponse response) throws IOException, BaseCheckedException {
		String channelId = request.getParameter("channelId");
		String tagTree = request.getParameter("tagTree");
		String parentName = request.getParameter("tagName");//被粘贴的标签名
		String tagDepth = request.getParameter("tagDepth");//
		String tagcut = (String) request.getSession().getAttribute("tagcut");
		if (tagcut == null){
			tagcut = "";
			logger.error("error:粘贴失败：请先剪切再粘贴");
			response.getWriter().write("'error:粘贴失败：请先剪切再粘贴");
			throw new BaseCheckedException("", "请先剪切再粘贴");
		}
		String[] tagcuts = tagcut.split(",");
		String originalChannelId = tagcuts[0];
		String originalTagName = tagcuts[1];
		if (!StringUtil.isEmpty(tagTree) && tagTree.indexOf(","+originalTagName+",")> -1) {
			logger.error("error:父标签不能剪切到子标签");
			response.getWriter().write("error:粘贴失败：父标签不能剪切到子标签");
			throw new BaseCheckedException("", "error:粘贴失败：父标签不能剪切到子标签");
		}
		int newTagTreeDepath = Integer.parseInt(tagDepth) + tagService.getMaxDepthOfSonTag(originalChannelId, originalTagName);
		if (newTagTreeDepath > 5) {
			logger.error("error:粘贴失败，原因：粘贴后标签的层数超过五层。默认标签不能超过五级");
			response.getWriter().write("error:粘贴失败，原因：粘贴后标签的层数超过五层。默认标签不能超过五级");
			throw new BaseCheckedException("", "error:粘贴失败，原因：粘贴后标签的层数超过五层。默认标签不能超过五级");
		}
		tagService.pasteTag(channelId, parentName, originalChannelId, originalTagName);
	}
	@RequestMapping(value = "/tag/isExist", method = RequestMethod.GET)
	public void isExist(HttpServletRequest request,HttpServletResponse response) throws IOException {
		String channelId = request.getParameter("channelId");
		String tagName = request.getParameter("tagName");//被粘贴的标签名
		boolean isExist = tagService.isExist(channelId, tagName);
		response.getWriter().write(String.valueOf(isExist));
	}
	
	/**
	 * 根据父标签和标签名称,得到标签的层级结构(tree)
	 * @param parentName
	 * @param tagName
	 * @return
	 */
	private String getTree(String parentTree , String  tagName){
		if("".equals(parentTree) || parentTree == null ){
			return "," + tagName+",";
		}
		return parentTree +  tagName +",";
	}
	
	
	
}
